<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="'/home'">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="slotProps">
            <el-row
              v-for="(v1, i1) in slotProps.row.children"
              :key="v1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
            >
              <el-col :span="5">
                <el-tag closable @close="delRights(slotProps.row, v1)">{{ v1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(v2, i2) in v1.children" :key="v2.id" :class="[i2 === 0 ? '' : 'bdtop']">
                  <el-col :span="8">
                    <el-tag closable type="success" @close="delRights(slotProps.row, v2)">{{ v2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      v-for="v3 in v2.children"
                      :key="v3.id"
                      closable
                      type="warning"
                      @close="delRights(slotProps.row, v3)"
                      >{{ v3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="slotProps">
            <el-button type="primary" size="mini" icon="el-icon-edit"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="showSetRightsDialog(slotProps.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="分配权限" :visible.sync="setRightsDialog.visible" width="50%">
      <div>
        <el-tree
          ref="rightsTree"
          :data="setRightsDialog.rightsList"
          :props="setRightsDialog.treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="setRightsDialog.defCheckedNodeIdArr"
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="saveRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      roleList: [],
      setRightsDialog: {
        visible: false,
        curRole: null,
        rightsList: [],
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        defCheckedNodeIdArr: []
      }
    }
  },
  methods: {
    async saveRights() {
      const arr1 = this.$refs.rightsTree.getCheckedKeys()
      const arr2 = this.$refs.rightsTree.getHalfCheckedKeys()
      const arr3 = arr1.concat(arr2)
      const { data: res } = await this.$http.post(`roles/${this.setRightsDialog.curRole.id}/rights`, {
        rids: arr3.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.setRightsDialog.visible = false
      this.loadRoleList()
    },
    // 复杂数据类型，在传参的时候，传递的是内存地址
    getLeafIdArr(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(v => {
        // 递归调用：自己调用自己
        this.getLeafIdArr(v, arr)
      })
    },
    async showSetRightsDialog(role) {
      const { data: res } = await this.$http.get(`rights/tree`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }

      this.setRightsDialog.defCheckedNodeIdArr = []

      const ids = []
      this.getLeafIdArr(role, ids)
      this.setRightsDialog.defCheckedNodeIdArr = ids

      this.setRightsDialog.rightsList = res.data
      this.setRightsDialog.curRole = role
      this.setRightsDialog.visible = true
    },
    async delRights(role, rights) {
      const result = await this.$confirm(`此操作将永久删除权限："${rights.authName}"，是否继续？`, '提示', {
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rights.id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')

      role.children = res.data
    },
    async loadRoleList() {
      const { data: res } = await this.$http.get('/roles')
      console.log(res, 'roles list res')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    }
  },
  created() {
    this.loadRoleList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px 7px 7px 0;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.el-row {
  display: flex;
  align-items: center;
}
</style>
